<template>
  <div v-if="roleName=='管理员'" class="dashboard-container">
    <h1 style="text-align: center">员工信息管理</h1>
    <!--    <h1>第一种参数获取：{{userName}}</h1>-->
    <!--    <h1>第二种参数获取：{{this.userName}}</h1>-->
    <el-dialog
      :visible.sync="addButtonController"
      title="新增"
      width="50%"
      @close="closeUser('ruleForm')"
    >
      <el-form ref="ruleForm" :model="addList" :rules="roles" label-width="20%">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="addList.userName" clearable maxlength="20" placeholder="请输入用户名称" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addList.sex">
            <el-radio label="男" value="男">男</el-radio>
            <el-radio label="女" value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="addList.userPassword" clearable maxlength="20" placeholder="请输入密码" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="addList.phoneNumber" clearable maxlength="11" placeholder="请输入手机号" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="addList.idCard" clearable maxlength="18" placeholder="请输入身份证" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addList.remark" clearable maxlength="100" placeholder="请输入备注" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="addUser('ruleForm')">确 定</el-button>
    <el-button @click="closeUser('ruleForm')">取 消</el-button>
  </span>
    </el-dialog>
    <el-button
      plain style="width:80px; margin-bottom:30px;margin-left:10%; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 8px; background-color: #cfefc6; margin-top: 20px" @click="addButton">
      新增
    </el-button>
    <el-dialog
      :visible.sync="updateButtonController"
      title="修改"
      width="30%"
      @close="closeUser('ruleForm')"
    >
      <el-form ref="ruleForm" :model="updateList" :rules="roles" label-width="20%">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="updateList.userName" clearable maxlength="20" placeholder="请输入用户名称" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="updateList.sex">
            <el-radio label="男" value="男">男</el-radio>
            <el-radio label="女" value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="updateList.userPassword" clearable maxlength="20" placeholder="请输入密码" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="updateList.phoneNumber" clearable maxlength="11" placeholder="请输入手机号" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="updateList.idCard" clearable maxlength="18" placeholder="请输入身份证" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="updateList.remark" clearable maxlength="100" placeholder="请输入备注" show-word-limit
                    style="width: 80%"/>
        </el-form-item>
      </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="updateUser('ruleForm')">确 定</el-button>
    <el-button @click="closeUser('ruleForm')">取 消</el-button>
  </span>

    </el-dialog>


    <el-dialog
      :visible.sync="deleteButtonController"
      title="您确认要删除吗？"
      width="30%"
      @close="closeUser('ruleForm')"
    >
      <el-form ref="ruleForm" :model="deleteUserId" :rules="roles" label-width="20%"></el-form>

      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="deleteUser('ruleForm')">确 定</el-button>
    <el-button @click="closeDelete('ruleForm')">取 消</el-button>
  </span>

    </el-dialog>
    <el-input
      v-model="userId2"
      clearable
      name="username"
      placeholder="用户ID"
      style="margin-left:40px ;width: 180px"
      type="text"
    />
    <el-input
      v-model="userName2"
      clearable
      name="username"
      placeholder="用户姓名"
      style="margin-left:40px ;width: 180px"
      type="text"
    />
    <el-select v-model="roleName2" clearable placeholder="请选择角色" style="margin-left:40px ;width: 180px">
      <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"/>
    </el-select>
    <el-button plain style="width:80px; margin-bottom:10px;margin-left:40px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 8px; background-color: #cfefc6; margin-top: 20px" @click="selectUser">查询
    </el-button>
    <el-button style="width:80px;margin-bottom:20px;margin-left:40px ; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 8px;" @click="checkUser">重置
    </el-button>
    <el-table :data="userList.slice((currentPage-1)*pagesize,currentPage*pagesize)" border height="590px"
              style="width: 100%;margin-top: 10px;border-radius: 8px;overflow: hidden;">
      <el-table-column align="center" fixed label="用户ID" prop="userId" width="150"/>
      <el-table-column align="center" fixed label="用户名" prop="userName" width="150"/>
      <el-table-column align="center" fixed label="用户密码" prop="userPassword" width="150"/>
      <el-table-column align="center" fixed label="角色" prop="roleName" width="150"/>
      <el-table-column align="center" fixed label="性别" prop="sex" width="130"/>
      <el-table-column align="center" fixed label="手机号" prop="phoneNumber" width="180"/>
      <el-table-column align="center" fixed label="身份证" prop="idCard" width="190"/>
      <el-table-column align="center" fixed label="备注" prop="remark" min-width="80"/>
      <el-table-column align="center" fixed label="操作" width="150">
        <template v-slot="scope">
          <el-button icon="el-icon-edit" round size="mini" @click="updateButton(scope.row)"></el-button>
          <el-button icon="el-icon-delete" round size="mini" @click="deleteButton(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:5px;margin-left: 30%;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,8,10,15,20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userList.length">
      </el-pagination>
    </div>
  </div>
  <div v-else="'没有权限访问'">
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {deleteUser, insertUser, selectAllUser, updateUser} from '@/api/user'

export default {
  name: 'users',
  computed: {
    ...mapGetters([
      'userId',
      'userName',
      'roleName'
    ])
  },
  data() {// 页面参数
    return {
      userId1: this.$store.getters.userId,
      userName1: this.$store.getters.userName,
      roleName1: this.$store.getters.roleName,
      userId2: '',
      userName2: '',
      roleName2: '',
      roleList: [{
        value: '员工',
        label: '员工'
      }, {
        value: '管理员',
        label: '管理员'
      }],
      userList: [],
      addButtonController: false,
      addList: {
        userName: '',
        userPassword: '',
        sex: '',
        phoneNumber: '',
        idCard: '',
        remark: ''
      },
      updateButtonController: false,
      updateList: {
        userId: '',
        userTableId: '',
        roleId: '',
        userName: '',
        userPassword: '',
        sex: '',
        phoneNumber: '',
        idCard: '',
        remark: ''
      },
      roles: {
        userName: [
          {required: true, trigger: 'blur', message: '用户名不能为空'},
          {min: 1, max: 20, message: '用户名长度在1-20个字符之间', trigger: 'blur'}
        ],
        sex: [
          {required: true, trigger: 'blur', message: '性别不能为空'},
        ],
        userPassword: [
          {required: true, trigger: 'blur', message: '密码不能为空'},
          {min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, trigger: 'blur', message: '手机号不能为空'},
          {min: 11, max: 11, message: '手机号长度11个字符', trigger: 'blur'}
        ],
        idCard: [
          {required: true, trigger: 'blur', message: '身份证不能为空'},
          {min: 18, max: 18, message: '身份证长度18个字符', trigger: 'blur'}
        ],
      },
      deleteButtonController: false,
      deleteUserId: '',
      currentPage: 1,
      currentIndex: '',
      pagesize: 10,
    }
  },// 页面初始化时加载的方法（打开时默认加载的方法）
  mounted() {
    this.selectUser()
    if (this.roleName !== '管理员') {
      this.$message.warning('您不是管理员，本页面仅限管理员可使用');
    } else {
      this.selectUser();
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pagesize = val;
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage= val
    },
// 页面的方法和事件
    selectUser() {
      selectAllUser({
        userId: this.userId2,
        userName: this.userName2,
        roleName: this.roleName2,
      }).then(
        response => {
          console.log(response.data)
          this.userList = response.data
        }
      )
    },
    checkUser() {
      this.userId2 = ''
      this.userName2 = ''
      this.roleName2 = ''
      this.selectUser()
    },
    addButton() {
      this.addList = {
        userName: '',
        userPassword: '',
        sex: '',
        phoneNumber: '',
        idCard: '',
        remark: ''
      }
      this.addButtonController = true
    },
    updateButton(row) {
      this.updateList = {
        userId: row.userId,
        userTableId: row.userTableId,
        roleId: row.roleId,
        userName: row.userName,
        userPassword: row.userPassword,
        sex: row.sex,
        phoneNumber: row.phoneNumber,
        idCard: row.idCard,
        remark: row.remark
      }
      this.updateButtonController = true
    },
    deleteButton(row) {
      this.deleteUserId = row.userId,
        this.deleteButtonController = true
    },
    addUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          insertUser({
            userName: this.addList.userName,
            sex: this.addList.sex,
            userPassword: this.addList.userPassword,
            phoneNumber: this.addList.phoneNumber,
            idCard: this.addList.idCard,
            remark: this.addList.remark
          }).then(
            response => {
              this.addButtonController = false
              this.$message.success('新增成功')
              this.selectUser()
            }
          )

        } else {
          return false
        }
      })
    },
    updateUser(formName) {
      // 获取表单实例，并验证表单数据是否有效
      this.$refs[formName].validate((valid) => {
        // 如果表单数据有效
        if (valid) {
          // 调用 updateUser 接口更新用户信息
          updateUser({
            userTableId: this.updateList.userTableId,
            userId: this.updateList.userId,
            roleId: this.updateList.roleId,
            userName: this.updateList.userName,
            sex: this.updateList.sex,
            userPassword: this.updateList.userPassword,
            phoneNumber: this.updateList.phoneNumber,
            idCard: this.updateList.idCard,
            remark: this.updateList.remark
          }).then(
            response => {
              // 更新完成后，禁用更新按钮
              this.updateButtonController = false
              if (this.updateList.userId = this.userId1) {
                this.$store.dispatch('user/updateUserName', this.updateList.userName)
              }
              this.$message.success('修改成功')
              // 重新加载用户列表数据
              this.selectUser()
            }
          )
        } else {
          return false
        }
      })
    },
    deleteUser() {
      deleteUser({
        userId: this.deleteUserId,
      }).then(
        async response => {
          this.deleteButtonController = false
          this.$message.success('删除成功')
          this.selectUser()
        }
      )
    },

    closeUser(formName) {
      this.$refs[formName].resetFields();
      this.addButtonController = false;
      this.updateButtonController = false;
    },
    closeDelete() {
      this.deleteButtonController = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
/* 定义一个优雅的房间表格样式 */
.elegant-room-table {
  /* 设置字体家族，确保文本的清晰和美观 */
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  /* 添加盒子阴影，增强表格的层次感 */
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.05);
  /* 设置圆角边界，使表格外观更加柔和 */
  border-radius: 8px;
  /* 允许内容溢出被隐藏，保持表格内容不超出显示区域 */
  overflow: hidden;

  /* 隐藏表格前的伪元素，保持界面的整洁 */
  &::before {
    display: none;
  }
}
</style>
